<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { axiosrmedical } from '../../http/axiosRead';
import { showToast } from 'vant';

const router = useRouter();
const route = useRoute();

const patientId = ref<number>(0);
const patientData = ref<any>(null);
const loading = ref<boolean>(false);
const timeRange = ref<string>('近一年');
const showTimeOptions = ref<boolean>(false);

// 初始化
onMounted(() => {
  const idParam = route.query.patientId;
  if (idParam) {
    patientId.value = Number(idParam);
    fetchRechargeRecords();
  } else {
    showToast('未获取到患者信息');
    router.replace('/recharge-card');
  }
});

// 获取充值记录
const fetchRechargeRecords = async (startDate?: string, endDate?: string) => {
  loading.value = true;
  try {
    const params: any = { patientId: patientId.value };
    if (startDate) params.startDate = startDate;
    if (endDate) params.endDate = endDate;

    const response = await axiosrmedical.get('/Payment/GetPatientBalance', {
      headers: { 'axiosrmedical': true },
      params
    });
    
    if (response.data.code === 200) {
      patientData.value = response.data.data;
    } else {
      showToast(response.data.msg || '获取充值记录失败');
    }
  } catch (error) {
    console.error('请求出错:', error);
    showToast('获取充值记录失败');
  } finally {
    loading.value = false;
  }
};

// 设置时间范围
const setTimeRange = (range: string) => {
  timeRange.value = range;
  showTimeOptions.value = false;
  
  // 根据选择的时间范围计算起止日期
  const now = new Date();
  let startDate: string | undefined;
  
  if (range === '近一年') {
    const lastYear = new Date();
    lastYear.setFullYear(now.getFullYear() - 1);
    startDate = lastYear.toISOString().split('T')[0];
  } else if (range === '近一个月') {
    const lastMonth = new Date();
    lastMonth.setMonth(now.getMonth() - 1);
    startDate = lastMonth.toISOString().split('T')[0];
  } else if (range === '近一周') {
    const lastWeek = new Date();
    lastWeek.setDate(now.getDate() - 7);
    startDate = lastWeek.toISOString().split('T')[0];
  }
  
  fetchRechargeRecords(startDate);
};

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
};
</script>

<template>
  <div class="records-page">
    <div class="header">
      <van-nav-bar
        title="门诊充值记录"
        left-arrow
        @click-left="router.back()"
      />
    </div>
    
    <div class="content">
      <van-loading v-if="loading" vertical>加载中...</van-loading>
      
      <template v-else-if="patientData">
        <div class="patient-info-card">
          <div class="patient-info-header">
            <div class="patient-name">{{ patientData.patientName }}</div>
            <div class="patient-phone">{{ patientData.phoneNumber }}</div>
          </div>
        </div>
        
        <div class="balance-card">
          <div class="balance-label">卡内余额</div>
          <div class="balance-value">¥{{ patientData.currentBalance.toFixed(2) }}</div>
        </div>
        
        <div class="filter-section">
          <van-dropdown-menu>
            <van-dropdown-item
              v-model="timeRange"
              :options="[
                { text: '近一年', value: '近一年' },
                { text: '近一个月', value: '近一个月' },
                { text: '近一周', value: '近一周' },
                { text: '自定义时间', value: '自定义时间' }
              ]"
              @change="setTimeRange"
            />
          </van-dropdown-menu>
        </div>
        
        <div class="records-list">
          <van-empty v-if="!patientData.rechargeRecords || patientData.rechargeRecords.length === 0" description="暂无充值记录" />
          
          <div v-else>
            <div v-for="(record, index) in patientData.rechargeRecords" :key="index" class="record-item">
              <div class="record-header">
                <span class="record-type">就诊卡充值</span>
                <span class="record-amount">+{{ record.amount.toFixed(2) }}</span>
              </div>
              <div class="record-footer">
                <span class="record-time">{{ formatDate(record.rechargeTime) }}</span>
                <span class="record-balance">余额{{ record.balanceAfter.toFixed(2) }}</span>
              </div>
            </div>
          </div>
        </div>
      </template>
      
      <div v-else class="no-data">
        <van-empty description="暂无数据" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.records-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.content {
  flex: 1;
  padding: 16px;
}

.patient-info-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.patient-info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.patient-name {
  font-size: 16px;
  font-weight: 500;
}

.patient-phone {
  color: #999;
  font-size: 14px;
}

.balance-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.balance-label {
  color: #666;
}

.balance-value {
  font-size: 18px;
  font-weight: 500;
}

.filter-section {
  margin-bottom: 16px;
}

.records-list {
  margin-top: 16px;
}

.record-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
}

.record-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.record-type {
  font-size: 16px;
  font-weight: 500;
}

.record-amount {
  color: #f56c6c;
  font-size: 16px;
  font-weight: 500;
}

.record-footer {
  display: flex;
  justify-content: space-between;
  color: #999;
  font-size: 14px;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}
</style> 